package com.hexb.cloud

import com.hexb.core.common.ResponseResult
import com.hexb.core.enums.AscColors
import com.hexb.core.exception.BusinessUnauthorizedException
import feign.FeignException
import feign.Response
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.ObjectFactory
import org.springframework.boot.autoconfigure.web.HttpMessageConverters
import org.springframework.cloud.netflix.feign.support.SpringDecoder
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl

import java.lang.reflect.Type

/**
 * @Package : com.hexb.core
 * @Author : hexb 
 * @Date : 2018-08-14 16:55
 */
class ResponseFeignDecoder extends SpringDecoder {

    static final private Logger logger = LoggerFactory.getLogger(SpringDecoder.class)

    ResponseFeignDecoder(ObjectFactory<HttpMessageConverters> messageConverters) {
        super(messageConverters)
    }

    @Override
    Object decode(Response response, Type type) throws IOException, FeignException {
        Object body = super.decode(response, ParameterizedTypeImpl.make(ResponseResult.class, [type] as Type[], ResponseResult.class))
        if (body instanceof ResponseResult) {
            ResponseResult result = body as ResponseResult
            if (result.status == ResponseResult.STATUS_FAILURE) {
                logger.error("${AscColors.RED} =====> ${AscColors.END}Feign Error: [ code = ${result.code} , message = ${result.message} ]")
                throw new BusinessUnauthorizedException(result.getMessage(), result.getCode())
            }
            if (type.getTypeName() == ResponseResult.class.getTypeName()) {
                return body
            }
            return body.data
        }
        return body
    }
}
